package com.sinopec.yelofixedreader.uhf

import com.sinopec.basemodule.constants.PreferencesConstant
import com.sinopec.iuhf.IUhfHelper
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.map

const val EmptyTAG = "EmptyTAG"
val INSERT_EMPTY = "(.{2})".toRegex()
/**
 * lwj at 2023/6/1
 * 读取编码
 */
fun IUhfHelper.readStringTags(): Flow<String> {
    val regex = PreferencesConstant.getInstance().rfid_regex.toRegex()
    return readTags { user, epc ->
        filter(user, epc, regex)
    }
        .filterNotNull()
        .filter {
            it.isNotEmpty()
        }.map {
            it.replace(INSERT_EMPTY,"$1 ").trimEnd()
        }
}

private fun filter(_user: String, _epc: String, regex: Regex): String {
    var user = _user
    val epc = _epc
    //先判断user的数据是否可以直接使用
    val isOk = if (!PalletCode.validationRfidRule(user, regex)) {
        //尝试从user区里面截取数据
        user = PalletCode.getScanCode(user) ?: ""
        if (!PalletCode.validationRfidRule(user, regex)) {
            //user取不到了 到这里尝试取epc的
            if (epc.length <= 17) {
                user = epc
                PalletCode.validationRfidRule(user, regex)
            } else {
                true
            }
        } else {
            true
        }
    } else {
        true
    }
    return if (isOk) user else ""
}